import React, { useRef, useState, useEffect } from 'react';
import { ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, message, Popconfirm, Tag, Space } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, FileTextOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import api from '../../services/api';
import { Document, KnowledgeBase } from '../../types';

const DocumentList: React.FC = () => {
  const actionRef = useRef<ActionType>(null);
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);

  useEffect(() => {
    fetchKnowledgeBases();
  }, []);

  const fetchKnowledgeBases = async () => {
    try {
      const response = await api.get('/knowledge-bases/', { params: { skip: 0, limit: 1000 } });
      const kbData = Array.isArray(response.data) ? response.data : response.data.items || [];
      setKnowledgeBases(kbData);
    } catch (error: any) {
      console.error('Failed to fetch knowledge bases:', error);
    }
  };

  const getKnowledgeBaseName = (kbId: number | undefined): string => {
    if (!kbId) return 'Unknown';
    const kb = knowledgeBases.find(k => k.id === kbId);
    return kb ? kb.name : `KB #${kbId}`;
  };

  const getKnowledgeBaseId = (record: any): number => {
    // 支持两种格式：snake_case 和 camelCase
    return record.knowledge_base_id || record.knowledgeBaseId || 0;
  };

  const fetchDocuments = async (params: any) => {
    try {
      const requestParams: any = {
        skip: (params.current - 1) * params.pageSize,
        limit: params.pageSize,
      };

      // 添加 Knowledge Base 过滤条件
      if (params.knowledge_base_id) {
        requestParams.knowledgeBaseId = params.knowledge_base_id;
      }

      const response = await api.get('/documents/', { params: requestParams });
      
      // 后端返回分页对象：{ items, total, page, page_size }
      const data = response.data;
      const documents = data.items || (Array.isArray(data) ? data : []);
      const total = data.total !== undefined ? data.total : documents.length;
      
      return {
        data: documents,
        success: true,
        total: total,
      };
    } catch (error: any) {
      message.error('Failed to fetch documents');
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  const handleDelete = async (id: number) => {
    setLoading(true);
    try {
      await api.delete(`/documents/${id}`);
      message.success('Document deleted successfully');
      actionRef.current?.reload();
    } catch (error: any) {
      message.error(error.response?.data?.detail || 'Failed to delete document');
    } finally {
      setLoading(false);
    }
  };

  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
  };

  const getChunkingModeColor = (mode: string): string => {
    const colors: Record<string, string> = {
      'fixed': 'blue',
      'semantic': 'green',
      'paragraph': 'orange',
      'none': 'default',
    };
    return colors[mode] || 'default';
  };

  const columns: ProColumns<Document>[] = [
    {
      title: 'Knowledge Base',
      dataIndex: 'knowledge_base_id',
      width: 200,
      valueType: 'select',
      valueEnum: knowledgeBases.reduce((acc, kb) => {
        acc[kb.id] = { text: kb.name };
        return acc;
      }, {} as Record<number, { text: string }>),
      render: (_, record) => {
        const kbId = getKnowledgeBaseId(record);
        return <Tag color="blue">{getKnowledgeBaseName(kbId)}</Tag>;
      },
      fieldProps: {
        placeholder: 'Select Knowledge Base',
        showSearch: true,
        allowClear: true,
      },
    },
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: 'File Name',
      dataIndex: 'filename',
      copyable: true,
      render: (_, record) => (
        <Space>
          <FileTextOutlined />
          {record.filename}
        </Space>
      ),
    },
    {
      title: 'File Type',
      dataIndex: 'file_type',
      width: 120,
      search: false,
      render: (_, record) => record.file_type ? (
        <Tag>{record.file_type.toUpperCase()}</Tag>
      ) : null,
    },
    {
      title: 'File Size',
      dataIndex: 'file_size',
      width: 120,
      search: false,
      render: (_, record) => formatFileSize(record.file_size),
    },
    {
      title: 'Chunking Mode',
      dataIndex: 'chunking_mode',
      width: 150,
      render: (_, record) => (
        <Tag color={getChunkingModeColor(record.chunking_mode)}>
          {record.chunking_mode.toUpperCase()}
        </Tag>
      ),
      valueEnum: {
        fixed: { text: 'Fixed' },
        semantic: { text: 'Semantic' },
        paragraph: { text: 'Paragraph' },
        none: { text: 'None' },
      },
    },
    {
      title: 'Chunk Size',
      dataIndex: 'chunk_size',
      width: 120,
      search: false,
      render: (_, record) => record.chunk_size || '-',
    },
    {
      title: 'Chunk Overlap',
      dataIndex: 'chunk_overlap',
      width: 120,
      search: false,
      render: (_, record) => record.chunk_overlap || '-',
    },
    {
      title: 'Uploaded At',
      dataIndex: 'uploaded_at',
      valueType: 'dateTime',
      width: 180,
      search: false,
    },
    {
      title: 'Action',
      valueType: 'option',
      width: 200,
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          icon={<EditOutlined />}
          onClick={() => navigate(`/documents/edit/${record.id}`)}
        >
          Edit
        </Button>,
        <Popconfirm
          key="delete"
          title="Are you sure to delete this document?"
          onConfirm={() => handleDelete(record.id)}
          okText="Yes"
          cancelText="No"
        >
          <Button type="link" danger icon={<DeleteOutlined />} loading={loading}>
            Delete
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <ProTable<Document>
      columns={columns}
      actionRef={actionRef}
      request={fetchDocuments}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      pagination={{
        defaultPageSize: 10,
        showSizeChanger: true,
      }}
      dateFormatter="string"
      headerTitle="Document Management"
      toolBarRender={() => [
        <Button
          key="button"
          icon={<PlusOutlined />}
          onClick={() => navigate('/documents/upload')}
          type="primary"
        >
          Upload Document
        </Button>,
      ]}
    />
  );
};

export default DocumentList;
